package com.bsh.serviceImpl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.bsh.api.ApiUtils;
import com.bsh.api.Exception.ApiException;
import com.bsh.api.params.DtoShop;
import com.bsh.mybatis.model.Merchant;
import com.bsh.mybatis.model.MerchantCategory;
import com.bsh.mybatis.model.MerchantImg;
import com.bsh.mybatis.model.User;
import com.bsh.repository.DaoMerchant;
import com.bsh.service.AccountService;
import com.bsh.service.ApiMerchantService;
import com.bsh.service.MerchantCategoryService;
import com.bsh.service.MerchantImgService;
import com.bsh.service.MerchantService;
import com.bsh.service.SmsService;
import com.bsh.service.UserService;
import com.bsh.utils.ApiMessage;
import com.bsh.utils.Des3;
import com.bsh.utils.Pager;
import com.bsh.utils.UploadUtils;

@Service
public class ApiMerchantServiceImpl implements ApiMerchantService {
	private static Logger log = LoggerFactory.getLogger(ApiMerchantServiceImpl.class);
	@Autowired
	UserService servUser;
	@Autowired
	SmsService servSms;
	@Autowired
	AccountService accountServ;
	@Autowired
	MerchantService mercService;
	@Autowired
	MerchantCategoryService merchantCateServ;
	@Autowired
	MerchantImgService merchantImgService;
	@Autowired
	DaoMerchant daoMerchant;

	@Override
	public ApiMessage registerMerchant(JSONObject dto, MultipartFile idcardA, MultipartFile idcardB,
			MultipartFile certificate, MultipartFile imgCover, MultipartFile showImg1, MultipartFile showImg2) throws ApiException {
		ApiMessage msg = null;
	    ApiUtils.checkUserNameToken(dto);
		if (ApiUtils.objIsEmpty(dto.getString("merchantName")) ) {
			throw new ApiException("400", "请填写商户全称");
		}
		if (ApiUtils.objIsEmpty(dto.getString("mobile"))) {
			throw new ApiException("400", "请填写联系人电话");
		}
		if (dto.getInteger("category") == null || dto.getInteger("category") == 0) {
			throw new ApiException("400", "请选择类型");
		}
		if (ApiUtils.objIsEmpty(dto.getString("traderDesc"))) {
			throw new ApiException("400", "请填写商家描述");
		}
		if (ApiUtils.objIsEmpty(dto.getString("address"))) {
			throw new ApiException("400", "请填写详细地址");
		}
		
		User userInfo = servUser.getUserByName(dto.getString("userName"));
		if (userInfo == null) {
			throw new ApiException("400", "用户不存在");
		}
		if (!userInfo.getLevel().equals("gold")) {
			throw new ApiException("400", "只有金钻会员才能申请商户");
		}

		// 保存图片
		String idcardAUrl = "";
		if (!idcardA.isEmpty()) {
			idcardAUrl = UploadUtils.save(idcardA, "/upload/private/merchant/IDCARD/" + userInfo.getId());
		} else {
			throw new ApiException("400", "请上传证件正面照");
		}
		String idcardBUrl = "";
		if (!idcardB.isEmpty()) {
			idcardBUrl = UploadUtils.save(idcardB, "/upload/private/merchant/IDCARD/" + userInfo.getId());
		} else {
			throw new ApiException("400", "请上传证件背面照");
		}
		String certificateUrl = "";
		if (!certificate.isEmpty()) {
			certificateUrl = UploadUtils.save(certificate, "/upload/private/merchant/IDCARD/" + userInfo.getId());
		} else {
			throw new ApiException("400", "请上传营业执照");
		}
		String imgCoverUrl = "";
		if (!imgCover.isEmpty()) {
			imgCoverUrl = UploadUtils.save(imgCover, "/upload/public/merchant/imgCover/" + userInfo.getId());
		} else {
			throw new ApiException("400", "请上传商家形象照");
		}
		// 检查名称是否存在
		Merchant checkName = mercService.getMerchantByName(dto.getString("name"));
		if (checkName != null) {
			throw new ApiException("400", dto.getString("name") + " 名称已存在");
		}
		Merchant checkMerchantName = mercService.getMerchantByMerchantName(dto.getString("merchantName"));
		if (checkMerchantName != null) {
			throw new ApiException("400", dto.getString("merchantName") + " 名称已存在");
		}

		//
		Merchant merchantReg = new Merchant();
		merchantReg.setName(dto.getString("name"));
		merchantReg.setMerchantName(dto.getString("merchantName"));
		merchantReg.setCategory(dto.getInteger("category"));
		merchantReg.setTraderDesc(dto.getString("traderDesc"));
		merchantReg.setProvince(dto.getInteger("province"));
		merchantReg.setCity(dto.getInteger("city"));
		merchantReg.setArea(dto.getInteger("area"));
		merchantReg.setAddress(dto.getString("address"));
		merchantReg.setLinkman(dto.getString("linkman"));
		merchantReg.setMobile(dto.getString("mobile"));
		merchantReg.setStatus(0);
		merchantReg.setCountry(1); // 国家
		merchantReg.setCreateTime(new Date());
		merchantReg.setCertificateNum(dto.getString("certificateNum"));
		if (ApiUtils.objIsEmpty(dto.getShort("certificateType"))) {
			merchantReg.setCertificateType((short) dto.getShort("certificateType"));
		}

		// 图片
		merchantReg.setIdcardA(idcardAUrl);
		merchantReg.setIdcardB(idcardBUrl);
		merchantReg.setCertificate(certificateUrl);
		merchantReg.setImgCover(imgCoverUrl);
		merchantReg.setUserid(userInfo.getId());
		Integer insertId = mercService.apiAddMerchant(merchantReg);

		if (insertId != null) {
			msg = new ApiMessage("200", "申请成功");
		} else {
			throw new ApiException("400", "申请失败");
		}
		// 保存商户照片
		MerchantImg img = new MerchantImg();
		String showImg1Url = "";
		if (ApiUtils.objIsEmpty(showImg1)) {
			showImg1Url = UploadUtils.save(showImg1, "/upload/private/merchant/show/" + userInfo.getId());
			img.setMerchantId(insertId);
			img.setUrl(showImg1Url);
			img.setSort(1);
			img.setCreateTime(new Date());
			merchantImgService.addMerchantImg(img);
		}
		String showImg2Url = "";
		if (ApiUtils.objIsEmpty(showImg2)) {
			showImg2Url = UploadUtils.save(showImg2, "/upload/private/merchant/show/" + userInfo.getId());
			img.setMerchantId(insertId);
			img.setUrl(showImg2Url);
			img.setSort(2);
			img.setCreateTime(new Date());
			merchantImgService.addMerchantImg(img);
		}
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("token", dto.getString("token"));
		msg.setData(Des3.encResponse(data));

		return msg;
	}

	@Override
	public ApiMessage merchantCategory(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		msg = new ApiMessage("200", "商户类型列表");
		List<MerchantCategory> categoryList = merchantCateServ.getCategoryList();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("info", categoryList);
		msg.setData(Des3.encResponse(data));
		return msg;
	}

	@Override
	public ApiMessage merchantDetail(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
	    ApiUtils.checkUserNameToken(dto);
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}

		List<Map<String, Object>> list = mercService.getMerchantByUserId(user.getId());
		Map<String, Object> merchantInfo = new HashMap<String, Object>();
		if (list.size() > 0) {
			merchantInfo = list.get(0);
			String certificate = (String) merchantInfo.get("certificate");
			String img_cover = (String) merchantInfo.get("img_cover");
			String img_cover_small = (String) merchantInfo.get("img_cover_small");
			String idcard_a = (String) merchantInfo.get("idcard_a");
			String idcard_b = (String) merchantInfo.get("idcard_b");
			String showImg1 = (String) merchantInfo.get("showImg1");
			String showImg2 = (String) merchantInfo.get("showImg2");

			merchantInfo.remove("certificate");
			merchantInfo.remove("img_cover");
			merchantInfo.remove("img_cover_small");
			merchantInfo.remove("idcard_a");
			merchantInfo.remove("idcard_b");
			merchantInfo.remove("showImg1");
			merchantInfo.remove("showImg2");

			merchantInfo.put("certificate",  dto.getString("serv_ip")+certificate);
			merchantInfo.put("img_cover", dto.getString("serv_ip")+img_cover);
			merchantInfo.put("img_cover_small",  dto.getString("serv_ip")+img_cover_small);
			merchantInfo.put("idcard_a",  dto.getString("serv_ip")+idcard_a);
			merchantInfo.put("idcard_b",  dto.getString("serv_ip")+idcard_b);
			merchantInfo.put("showImg1",  dto.getString("serv_ip")+showImg1);
			merchantInfo.put("showImg2",  dto.getString("serv_ip")+showImg2);

		}
		msg = new ApiMessage("200", "查询成功");
		JSONObject data = new JSONObject();
		data.put("merchantInfo", merchantInfo);
		msg.setData(data.toJSONString());
		return msg;
	}

	@Override
	public ApiMessage changeMerchantDetail(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
	    ApiUtils.checkUserNameToken(dto);

		if (ApiUtils.objIsEmpty(dto.getString("merchantName"))) {
			throw new ApiException("400", "请填写商户全称");
		}
		if (ApiUtils.objIsEmpty(dto.getString("mobile"))) {
			throw new ApiException("400", "请填写联系人电话");
		}
		if (ApiUtils.objIsEmpty(dto.getInteger("category")) || dto.getInteger("category") == 0) {
			throw new ApiException("400", "请选择类型");
		}
		if (ApiUtils.objIsEmpty(dto.getString("traderDesc"))) {
			throw new ApiException("400", "请填写商家描述");
		}
		if (ApiUtils.objIsEmpty(dto.getString("address"))) {
			throw new ApiException("400", "请填写详细地址");
		}
		if (ApiUtils.objIsEmpty(dto.getString("certificateNum"))) {
			throw new ApiException("400", "请填写身份证号码");
		}
		if (ApiUtils.objIsEmpty(dto.getString("idcardAUrl"))) {
			throw new ApiException("400", "请上传证件正面照");
		}
		if (ApiUtils.objIsEmpty(dto.getString("idcardBUrl"))) {
			throw new ApiException("400", "请上传证件背面照");
		}
		if (ApiUtils.objIsEmpty(dto.getString("certificateUrl"))) {
			throw new ApiException("400", "请上传营业执照");
		}
		if (ApiUtils.objIsEmpty(dto.getString("imgCoverUrl"))) {
			throw new ApiException("400", "请上传商家形象照");
		}

		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}

		List<Map<String, Object>> list = mercService.getMerchantByUserId(user.getId());
		Map<String, Object> merchantInfo = new HashMap<String, Object>();
		if (ApiUtils.objIsNotEmpty(list)) {
			merchantInfo = list.get(0);
		} else {
			throw new ApiException("102", "商户不存在");
		}

		// 通过查询出的商家信息找到对应的商家
		Integer mid = (Integer) merchantInfo.get("id");
		Merchant merchant = mercService.getMerchant(mid);
		if (merchant.getStatus() == 0) {
			throw new ApiException("102", "商户正在审核中,请等待审核完成");
		}
		//保存商家信息
		merchant.setName(dto.getString("name"));
		merchant.setMerchantName(dto.getString("merchantName"));
		merchant.setCategory(dto.getInteger("category"));
		merchant.setTraderDesc(dto.getString("traderDesc"));
		merchant.setProvince(dto.getInteger("province"));
		merchant.setCity(dto.getInteger("city"));
		merchant.setArea(dto.getInteger("area"));
		merchant.setAddress(dto.getString("address"));
		merchant.setLinkman(dto.getString("linkman"));
		merchant.setMobile(dto.getString("mobile"));
		merchant.setStatus(0);
		merchant.setTraderDesc(dto.getString("traderDesc"));
		merchant.setCertificateNum(dto.getString("certificateNum"));
		String idcardAUrl = merchant.getIdcardA();
		if (!dto.getString("idcardAUrl").equals(dto.getString("serv_ip")+merchant.getIdcardA())) {
			idcardAUrl = ApiUtils.removeImageUrl(dto.getString("idcardAUrl"), dto.getString("serv_ip"));
		}
		String idcardBUrl = merchant.getIdcardB();
		if (!dto.getString("idcardBUrl").equals(dto.getString("serv_ip")+merchant.getIdcardB())) {
			idcardBUrl = ApiUtils.removeImageUrl(dto.getString("idcardBUrl"),  dto.getString("serv_ip"));
		}
		String certificateUrl = merchant.getCertificate();
		if (!dto.getString("certificateUrl").equals(dto.getString("serv_ip")+merchant.getCertificate())) {
			certificateUrl = ApiUtils.removeImageUrl(dto.getString("certificateUrl"),  dto.getString("serv_ip"));
		}
		String imgCoverUrl = merchant.getImgCover();
		if (!dto.getString("imgCoverUrl").equals(dto.getString("serv_ip")+merchant.getImgCover())) {
			imgCoverUrl = ApiUtils.removeImageUrl(dto.getString("imgCoverUrl"), dto.getString("serv_ip"));
		}

		merchant.setIdcardA(idcardAUrl);
		merchant.setIdcardB(idcardBUrl);
		merchant.setCertificate(certificateUrl);
		merchant.setImgCover(imgCoverUrl);
		merchant.setModifyTime(new Date());
		mercService.changeMerchantInfo(merchant);
		
		
		
		//保存商家展示图片
		MerchantImg merchantImg = new MerchantImg();
		String showImg1Url = "";
		Integer imgId1 = null;
		Integer imgId2 = null;
		showImg1Url = ApiUtils.removeImageUrl(dto.getString("showImg1Url"),  dto.getString("serv_ip"));
		if(ApiUtils.objIsNotEmpty(merchantInfo.get("imgId1"))){
			imgId1 = (Integer) merchantInfo.get("imgId1");
			merchantImg.setId(imgId1);
			merchantImg.setUrl(showImg1Url);
			merchantImgService.updateMerchantImgUrl(merchantImg);
		}else{
			merchantImg.setMerchantId(merchant.getId());
			merchantImg.setUrl(showImg1Url);
			merchantImg.setSort(1);
			merchantImg.setCreateTime(new Date());
			merchantImgService.addMerchantImg(merchantImg);
		}
		String showImg2Url = "";
		showImg2Url = ApiUtils.removeImageUrl(dto.getString("showImg2Url"),  dto.getString("serv_ip"));
		merchantImg=new MerchantImg();
		if(ApiUtils.objIsNotEmpty(merchantInfo.get("imgId2"))){
			imgId2 = (Integer) merchantInfo.get("imgId2");
			merchantImg.setId(imgId2);
			merchantImg.setUrl(showImg2Url);
			merchantImgService.updateMerchantImgUrl(merchantImg);
		}else{
			merchantImg.setMerchantId(merchant.getId());
			merchantImg.setUrl(showImg2Url);
			merchantImg.setSort(2);
			merchantImg.setCreateTime(new Date());
			merchantImgService.addMerchantImg(merchantImg);
		}
		msg = new ApiMessage("200", "修改成功");
		return msg;
	}

	@Override
	public ApiMessage registerMerchantForUrl(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
	    ApiUtils.checkUserNameToken(dto);
		if (ApiUtils.objIsEmpty(dto.getString("merchantName")) ) {
			throw new ApiException("400", "请填写商户全称");
		}
		if (ApiUtils.objIsEmpty(dto.getString("mobile"))) {
			throw new ApiException("400", "请填写联系人电话");
		}
		if (dto.getInteger("category") == null || dto.getInteger("category") == 0) {
			throw new ApiException("400", "请选择类型");
		}
		if (ApiUtils.objIsEmpty(dto.getString("traderDesc"))) {
			throw new ApiException("400", "请填写商家描述");
		}
		if (ApiUtils.objIsEmpty(dto.getString("address"))) {
			throw new ApiException("400", "请填写详细地址");
		}
		
		User userInfo = servUser.getUserByName(dto.getString("userName"));
		if (userInfo == null) {
			throw new ApiException("400", "用户不存在");
		}
		if (!userInfo.getLevel().equals("gold")) {
			throw new ApiException("400", "只有金钻会员才能申请商户");
		}

		// 保存图片
		String idcardAUrl = "";
		if(ApiUtils.objIsEmpty(dto.getString("idcardA"))){
			throw new ApiException("400", "请上传证件正面照");
		}else {
			idcardAUrl = ApiUtils.removeImageUrl(dto.getString("idcardA"),dto.getString("serv_ip"));
		}
		
		
		String idcardBUrl = "";
		if(ApiUtils.objIsEmpty(dto.getString("idcardB"))){
			throw new ApiException("400", "请上传证件背面照");
		}else {
			idcardBUrl = ApiUtils.removeImageUrl(dto.getString("idcardB"),dto.getString("serv_ip"));
		}
		
		

		String certificateUrl = "";
		if(ApiUtils.objIsEmpty(dto.getString("certificate"))){
			throw new ApiException("400", "请上传营业执照");
		}else {
			certificateUrl = ApiUtils.removeImageUrl(dto.getString("certificate"),dto.getString("serv_ip"));
		}
		
		
		String imgCoverUrl = "";
		if(ApiUtils.objIsEmpty(dto.getString("imgCover"))){
			throw new ApiException("400", "请上传商家形象照");
		}else {
			imgCoverUrl = ApiUtils.removeImageUrl(dto.getString("imgCover"),dto.getString("serv_ip"));
		}
	
		// 检查名称是否存在
		Merchant checkName = mercService.getMerchantByName(dto.getString("name"));
		if (checkName != null) {
			throw new ApiException("400", dto.getString("name") + " 名称已存在");
		}
		Merchant checkMerchantName = mercService.getMerchantByMerchantName(dto.getString("merchantName"));
		if (checkMerchantName != null) {
			throw new ApiException("400", dto.getString("merchantName") + " 名称已存在");
		}

		//
		Merchant merchantReg = new Merchant();
		merchantReg.setName(dto.getString("name"));
		merchantReg.setMerchantName(dto.getString("merchantName"));
		merchantReg.setCategory(dto.getInteger("category"));
		merchantReg.setTraderDesc(dto.getString("traderDesc"));
		merchantReg.setProvince(dto.getInteger("province"));
		merchantReg.setCity(dto.getInteger("city"));
		merchantReg.setArea(dto.getInteger("area"));
		merchantReg.setAddress(dto.getString("address"));
		merchantReg.setLinkman(dto.getString("linkman"));
		merchantReg.setMobile(dto.getString("mobile"));
		merchantReg.setStatus(0);
		merchantReg.setCountry(1); // 国家
		merchantReg.setCreateTime(new Date());
		merchantReg.setCertificateNum(dto.getString("certificateNum"));
		if (ApiUtils.objIsEmpty(dto.getShort("certificateType"))) {
			merchantReg.setCertificateType((short) dto.getShort("certificateType"));
		}

		// 图片
		merchantReg.setIdcardA(idcardAUrl);
		merchantReg.setIdcardB(idcardBUrl);
		merchantReg.setCertificate(certificateUrl);
		merchantReg.setImgCover(imgCoverUrl);
		merchantReg.setUserid(userInfo.getId());
		Integer insertId = mercService.apiAddMerchant(merchantReg);

		if (insertId != null) {
			msg = new ApiMessage("200", "申请成功");
		} else {
			throw new ApiException("400", "申请失败");
		}
		// 保存商户照片
		MerchantImg img = new MerchantImg();
		
		
		if(ApiUtils.objIsNotEmpty(dto.getString("showImg1"))){
			String showImg1Url = ApiUtils.removeImageUrl(dto.getString("showImg1"),dto.getString("serv_ip"));
			img.setMerchantId(insertId);
			img.setUrl(showImg1Url);
			img.setSort(1);
			img.setCreateTime(new Date());
			merchantImgService.addMerchantImg(img);
		}
		
		if(ApiUtils.objIsNotEmpty(dto.getString("showImg2"))){
			String showImg1Url = ApiUtils.removeImageUrl(dto.getString("showImg2"),dto.getString("serv_ip"));
			img.setMerchantId(insertId);
			img.setUrl(showImg1Url);
			img.setSort(2);
			img.setCreateTime(new Date());
			merchantImgService.addMerchantImg(img);
		}
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("token", dto.getString("token"));
		msg.setData(Des3.encResponse(data));

		return msg;
	}

	@Override
	public ApiMessage H5MerchantList(JSONObject dto) throws ApiException {
		ApiMessage msg = new ApiMessage();
		Integer pageIndex = dto.getInteger("pageIndex") == null ? 1: dto.getInteger("pageIndex");
		Integer pageSize =  dto.getInteger("pageSize") == null ? 10: dto.getInteger("pageSize");
		Pager pager = new Pager(pageIndex, pageSize);
		DtoShop queryDto=new DtoShop();
		queryDto.setCategory(dto.getInteger("category"));
		queryDto.setCity(dto.getInteger("city"));
		queryDto.setPage(dto.getInteger("page"));
		queryDto.setKeyword(dto.getString("keyword"));
		List<Map<String, Object>> list = daoMerchant.apiH5GetShopList(pager, queryDto);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> nM = list.get(i);
			nM.put("imgCover",dto.getString("serv_ip")+(String) nM.get("imgCover") );
			nM.put("imgCoverSmall", dto.getString("serv_ip")+(String) nM.get("imgCoverSmall") );
		}

		msg = new ApiMessage("200", "h5商铺列表");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("shop_list", list);
		data.put("count", pager.getRowCount());
		data.put("total_page", pager.getPageCount());
		data.put("current_page", pageIndex);
		msg.setData(Des3.encResponse(data));

		return msg;
	}

	@Override
	public ApiMessage H5MerchantDetail(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		if(ApiUtils.objIsEmpty(dto.getString("merchant_id"))){
			throw new ApiException("400", "缺少商户id");
		}
		List<Map<String, Object>> list = daoMerchant.apiH5GetShopDetail(dto.getString("merchant_id"));
		Map<String, Object> nM = list.get(0);
		nM.put("imgCover",dto.getString("serv_ip")+(String) nM.get("imgCover"));
		nM.put("imgCoverSmall", dto.getString("serv_ip")+(String) nM.get("imgCoverSmall"));
		nM.put("showImg1",dto.getString("serv_ip")+(String) nM.get("showImg1"));
		nM.put("showImg2",dto.getString("serv_ip")+(String) nM.get("showImg2"));
		msg = new ApiMessage("200", "商铺详情");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("shop_detail", nM);
		msg.setData(Des3.encResponse(data));
		return msg;
	}

	@Override
	public ApiMessage H5MerchantHotList(JSONObject dto) throws ApiException {
		ApiMessage msg = new ApiMessage();
		List<Map<String, Object>> list = daoMerchant.apiH5GetHotShopList();
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> nM = list.get(i);
			nM.put("imgCover",dto.getString("serv_ip")+(String) nM.get("imgCover") );
			nM.put("imgCoverSmall", dto.getString("serv_ip")+(String) nM.get("imgCoverSmall") );
		}

		msg = new ApiMessage("200", "h5商铺列表");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("hot_list", list);
		msg.setData(Des3.encResponse(data));

		return msg;
	}

}
